<?php
namespace App\Services;
use App\Models\MaterialModel;
use App\Models\CourseTypeModel;

class MaterialService{
    /**
     * 获取资料总数
     * @param int $position
     * @return int $_count
     */
    public function getMaterialCount($position){
        $_count = MaterialModel::where('position',$position)->count();
        return $_count;
    }

	/**
	 * 添加资料
	 * @param $data
	 * @return bool $res
	 */
	public function insertMaterial($data){
		$res = MaterialModel::insert($data);
		return $res;
	}

	/**
	 * 获取资料列表
	 * @return $mlist 
	 */
	public function getMaterialList($pagesize,$keywords='',$position=-1){
		$mlist = MaterialModel::orderBy('id','asc')
				->where('isshow',1)
				->where(function($query) use ($keywords){
					if($keywords != ''){
						$query->where('banner_name', 'like', '%'.$keywords.'%');
					}
				})
                ->where(function($query) use($position){
                    if($position > -1){
                        $query->where('position',$position);
                    }
                })
				->paginate($pagesize);

		foreach($mlist as $mtm=>$mst){
		    if($mst->position == 0){
		        $mlist[$mtm]->postion_name = '推荐';
            }else{
		        $info = CourseTypeModel::where('id',$mst->position)->select('id','type_name')->first();
		        $mlist[$mtm]->position_name = $info->type_name;

		        unset($info);
            }
        }

		if(!empty($mlist)){
            return $mlist;
        }else{
		    return false;
        }
	}

	/**
	 * 获取资料详细信息
	 * @param int $id
	 * @param array $info
	 */
	public function getMaterialInfo($id){
		$info = MaterialModel::where('id',$id)->first()->toArray();
		return $info; 
	}

	/**
	 * 更新资料信息
	 * @param int $id
	 * @param array $data
	 * @return bool $res
	 */
	public function modifyMaterial($id,$data){
		$res = MaterialModel::where('id',$id)->update($data);
		return $res;
	}

}